package com.atguigu.tingshu.user.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.cache.GuiGuCache;
import com.atguigu.tingshu.common.constant.KafkaConstant;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.service.KafkaService;
import com.atguigu.tingshu.common.util.AuthContextHolder;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.user.*;
import com.atguigu.tingshu.user.mapper.*;
import com.atguigu.tingshu.user.service.UserInfoService;
import com.atguigu.tingshu.user.strategy.PaidRecordStrategy;
import com.atguigu.tingshu.user.strategy.StrategyFactory;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private WxMaService wxMaService;

    @Autowired
    private RedisTemplate redisTemplate;


    @Autowired
    private KafkaService kafkaService;

    @Autowired
    private UserPaidAlbumMapper userPaidAlbumMapper;

    @Autowired
    private UserPaidTrackMapper userPaidTrackMapper;

    @Autowired
    private AlbumFeignClient albumFeignClient;


    @Autowired
    private VipServiceConfigMapper vipServiceConfigMapper;

    @Autowired
    private UserVipServiceMapper userVipServiceMapper;

    /**
     * 小程序端携带微信接口访问临时票据获取微信用户唯一标识openId,完成登录
     *
     * @param code
     * @return
     */
    @Override
    public Map<String, String> wxLogin(String code) {
        try {
            //1.调用微信开发SDK提供WxMaService对象调用获取微信唯一标识接口 得到openId
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            if (sessionInfo != null) {
                String wxOpenid = sessionInfo.getOpenid();
                //2.根据获取到OpenID查询用户表是否存在用户记录
                LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(UserInfo::getWxOpenId, wxOpenid);
                UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);
                if (userInfo == null) {
                    //3.如果用户不存在-说明首次使用微信登录
                    //3.1 新增用户记录
                    userInfo = new UserInfo();
                    userInfo.setNickname("听友" + IdUtil.getSnowflakeNextId());
                    userInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
                    userInfo.setWxOpenId(wxOpenid);
                    userInfo.setIsVip(0);
                    userInfoMapper.insert(userInfo);
                    //3.2 TODO 基于MQ消息队列异步新增账户（余额）记录
                    kafkaService.sendMessage(KafkaConstant.QUEUE_USER_REGISTER, userInfo.getId().toString());
                }

                //4.封装登录成功后Token
                //4.1 声明用户登录key，生成随机令牌
                String token = IdUtil.fastSimpleUUID();
                String loginKey = RedisConstant.USER_LOGIN_KEY_PREFIX + token;

                //4.2 将用户信息存入Redis UserInfoVO
                UserInfoVo userInfoVo = BeanUtil.copyProperties(userInfo, UserInfoVo.class);
                redisTemplate.opsForValue().set(loginKey, userInfoVo, RedisConstant.USER_LOGIN_KEY_TIMEOUT, TimeUnit.SECONDS);

                //4.3 封装响应结果
                Map<String, String> mapResult = new HashMap<>();
                mapResult.put("token", token);
                return mapResult;
            }
        } catch (Exception e) {
            log.error("[用户服务]微信登录异常：{}", e);
            throw new RuntimeException(e);
        }
        return null;
    }


    /**
     * 获取当前登录用户信息
     *
     * @return
     */
    @Override
    @GuiGuCache(prefix = "userInfoVo:")
    public UserInfoVo getUserInfo() {
        //1.获取登录用户ID
        Long userId = AuthContextHolder.getUserId();
        //2.根据用户ID查询用户记录UserInfo
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //3.转为UserInfoVo返回
        return BeanUtil.copyProperties(userInfo, UserInfoVo.class);
    }

    /**
     * 根据用户ID获取用户（主播）基本信息
     *
     * @param userId
     * @return
     */
    @Override
    @GuiGuCache(prefix = "userInfoVo:")
    public UserInfoVo getUserInfoVoById(Long userId) {
        //2.根据用户ID查询用户记录UserInfo
        UserInfo userInfo = userInfoMapper.selectById(userId);
        //3.转为UserInfoVo返回
        return BeanUtil.copyProperties(userInfo, UserInfoVo.class);
    }


    /**
     * 更新用户个人基本信息
     *
     * @param userInfoVo
     * @param userId
     */
    @Override
    public void updateUser(UserInfoVo userInfoVo) {
        //1.获取登录用户ID 1
        Long userId = AuthContextHolder.getUserId();
        //采用延时双删确保数据库跟缓存一致性
        //①先删除一次缓存数据
        String key = "userInfoVo:" + userId + ":info";
        redisTemplate.delete(key);

        //②.业务限制只能修改头像跟昵称
        UserInfo userInfo = new UserInfo();
        userInfo.setId(userId);
        userInfo.setNickname(userInfoVo.getNickname());
        userInfo.setAvatarUrl(userInfoVo.getAvatarUrl());
        userInfoMapper.updateById(userInfo);


        //③睡眠一段时间 确保如果此时有并发查询 1 号用户信息，查询DB写入Redis缓存成功
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        //⑤再删除一遍缓存 并发读放入缓存“脏”数据删除
        redisTemplate.delete(key);
    }


    /**
     * 专辑下声音某一页中需要验证专辑或声音购买状态
     *
     * @param userId               用户ID
     * @param albumId              专辑ID
     * @param needCheckTrackIdList 需要检查声音购买状态ID集合(专辑下某一页声音ID列表)
     * @return Map<声音ID ， 购买状态>
     */
    @Override
    public Map<Long, Integer> userIsPaidTrack(Long userId, Long albumId, List<Long> needCheckTrackIdList) {
        //1.根据用户ID+专辑ID查询专辑购买记录
        LambdaQueryWrapper<UserPaidAlbum> userPaidAlbumLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getUserId, userId);
        userPaidAlbumLambdaQueryWrapper.eq(UserPaidAlbum::getAlbumId, albumId);
        Long count = userPaidAlbumMapper.selectCount(userPaidAlbumLambdaQueryWrapper);
        if (count > 0) {
            //2 如果用户购买该专辑则将 needCheckTrackIdList 购买状态：1
            Map<Long, Integer> buyStatusMap = new HashMap<>();
            for (Long trackId : needCheckTrackIdList) {
                buyStatusMap.put(trackId, 1);
            }
            return buyStatusMap;
        }
        //3. 未购买该专辑，继续查询用户购买声音记录
        LambdaQueryWrapper<UserPaidTrack> userPaidTrackLambdaQueryWrapper = new LambdaQueryWrapper<>();
        userPaidTrackLambdaQueryWrapper.eq(UserPaidTrack::getUserId, userId);
        userPaidTrackLambdaQueryWrapper.in(UserPaidTrack::getTrackId, needCheckTrackIdList);
        //3.1 用于已购声音记录
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(userPaidTrackLambdaQueryWrapper);
        //3.2 判断已购声音集合如果为空 将待检查声音ID购买状态：0
        if (CollectionUtil.isEmpty(userPaidTrackList)) {
            Map<Long, Integer> buyStatusMap = new HashMap<>();
            for (Long trackId : needCheckTrackIdList) {
                buyStatusMap.put(trackId, 0);
            }
            return buyStatusMap;
        }
        //3.3 待检查的声音ID中用户有购买，确定哪些是已购买 哪些是未购买
        List<Long> userPaidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
        Map<Long, Integer> buyStatusMap = new HashMap<>();
        for (Long needCheckTrackId : needCheckTrackIdList) {
            if (userPaidTrackIdList.contains(needCheckTrackId)) {
                //该声音已被用户购买
                buyStatusMap.put(needCheckTrackId, 1);
            } else {
                //该声音未被用户购买
                buyStatusMap.put(needCheckTrackId, 0);
            }
        }
        return buyStatusMap;
    }

    /**
     * 判断当前用户是否购买过指定专辑
     *
     * @param albumId 专辑ID
     * @param userId  用户ID
     * @return true:已购买 false：未购买
     */
    @Override
    public Boolean isPaidAlbum(Long userId, Long albumId) {
        LambdaQueryWrapper<UserPaidAlbum> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidAlbum::getUserId, userId);
        queryWrapper.eq(UserPaidAlbum::getAlbumId, albumId);
        Long count = userPaidAlbumMapper.selectCount(queryWrapper);
        return count > 0;
    }

    /**
     * 查询当前登录用户某个专辑已购声音ID列表
     *
     * @param albumId
     * @return
     */
    @Override
    public List<Long> getUserPaidTrackIdList(Long userId, Long albumId) {
        //1.根据用户ID+专辑ID查询已购声音表 得到已购声音集合
        LambdaQueryWrapper<UserPaidTrack> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserPaidTrack::getUserId, userId);
        queryWrapper.eq(UserPaidTrack::getAlbumId, albumId);
        List<UserPaidTrack> userPaidTrackList = userPaidTrackMapper.selectList(queryWrapper);
        //2.遍历得到已购声音ID列表
        if (CollectionUtil.isNotEmpty(userPaidTrackList)) {
            List<Long> userPaidTrackIdList = userPaidTrackList.stream().map(UserPaidTrack::getTrackId).collect(Collectors.toList());
            return userPaidTrackIdList;
        }
        return null;
    }


    @Autowired
    private StrategyFactory strategyFactory;


    /**
     * 处理不同购买项：VIP会员，专辑、声音
     *
     * @param userPaidRecordVo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void savePaidRecord(UserPaidRecordVo userPaidRecordVo) {
        //根据入参中购买项目类型获取不同策略实现类对象
        PaidRecordStrategy paidStrategy = strategyFactory.getPaidStrategy(userPaidRecordVo.getItemType());
        paidStrategy.savePaidRecord(userPaidRecordVo);
    }

    /**
     * 更新会员过期用户VIP标识
     *
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateVipExpireStatus() {
        //查询当日开始日期每天凌晨0点>会员过期时间
        DateTime today = DateUtil.beginOfDay(new Date());
        LambdaUpdateWrapper<UserInfo> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.lt(UserInfo::getVipExpireTime, today);
        updateWrapper.set(UserInfo::getIsVip, 0);
        this.update(updateWrapper);
    }

    public static void main(String[] args) {
        System.out.println(DateUtil.beginOfDay(new Date()));
    }
}
